package com.myFwk.filter;

import com.alibaba.fastjson.JSONObject;
import com.google.common.net.HttpHeaders;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Set;

/**
 * @Title:
 * @Description:
 * @Author: guowl
 * @version： 1.0
 * @Date:2021/8/26
 * @Copyright: Copyright(c)2021 RedaFlight.com All Rights Reserved
 */
@Component
public class TokenCheckFilter implements GlobalFilter, Ordered {

    /**
     *  请求白名单 不拦截的的URL
     */
    @Value("${no.require.urls:/admin/login}")
    private Set<String> noRequireTokenUrls;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 过滤拦截到用户的请求后做啥
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 检查接口是否需要token 才能访问
        if (isRequireToken(exchange)) {
            //放行 交给下一个步骤
             return chain.filter(exchange);
        }
        // 2. 取出用户的token
        String token = getUserToken(exchange);
        // 3 判断用户端的token 是否有效
        if (StringUtils.isEmpty(token)) {
            //无效token
            return builderNoAuthorizationResult(exchange);
        }
        //从redis中获取token 判断token是否有效，如果有效直接运行
        Boolean haskey = redisTemplate.hasKey(token);
        if (haskey != null && haskey) {
            //token有效直接放行
            return chain.filter(exchange);
        }

        //无效toke
        return builderNoAuthorizationResult(exchange);
    }

    /**
     * 判断该接口是否有效
     * @param exchange
     * @return
     */
    public boolean isRequireToken(ServerWebExchange exchange) {
        String path = exchange.getRequest().getURI().getPath();
        //判断是否包含这个URL
        boolean flag = noRequireTokenUrls.contains(path);
        return flag;
    }

    /**
     * 获取用户Token
     * @param exchange
     * @return
     */
    public String getUserToken(ServerWebExchange exchange) {
        String token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        return token == null ? null : token.replace("bearer ", "");
    }

    /**
     * 针对无效的Token 做出返回http 状态
     * 封装一个Http响应header 返回到
     * @param exchange
     * @return
     */
    public Mono<Void> builderNoAuthorizationResult(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().set("content", "application/json;charset=UTF-8");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error", "NoAuthorziation");
        jsonObject.put("errorMsg", "Token is Null or error");
        DataBuffer wrap = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
        return response.writeWith(Flux.just(wrap));
    }


    /**
     * 拦截器顺序
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
